package edu.neumont.App;

import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Timer;

import edu.neumont.entities.Entities;
import edu.utility.xuggle.MyAudio;
import edu.utility.xuggle.MyPicture;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MovieActivity extends Activity{
	public ImageView view;
	Thread t;
	Handler h;
	Timer timer;
	MyPicture picture;
	ObjectInputStream ois;
	int count = 0;
	int gcCount = 0;
	Runnable r;
	AudioTrack audioTrack;
	boolean playMovie;
	Button button;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.movie);
		try{
			view = (ImageView)findViewById(R.id.imageView1);
    		ois = new ObjectInputStream(Entities.network.getSocket().getInputStream());
		}catch(Exception ex){}	
		
		playMovie = false;
		
		
		r = new Runnable(){
			public void run() {	
				try{
					view.setImageBitmap(BitmapFactory.decodeByteArray(picture.getBytes(), 0, picture.getBytes().length));
				}catch(Exception ex){}
			}
		};
		h = new Handler();
		t = new Thread(new Runnable(){
			public void run() {
				audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, 40000, AudioTrack.MODE_STREAM);
				audioTrack.play();
				while(playMovie){
					try{
						Object o =  ois.readObject();
						if(o instanceof MyPicture){
							picture = (MyPicture)o;
							count++;
							if(count == 100){
								ois.reset();
								count = 0;
							}
						}
						else{
							MyAudio audio = (MyAudio)o;
							audioTrack.write(audio.getBytes(), 0, audio.getBytes().length);
						}
					}catch(Exception ex){}
					h.post(r);
				}
				audioTrack.pause();
			}
		});
	
	
	button = (Button)findViewById(R.id.playMovie);
	button.setOnClickListener(new View.OnClickListener(){
		public void onClick(View v) {
			if(!playMovie){
				playMovie = true;
				t.start();
				button.setText("stop");
			}else{
				try{
					PrintWriter writer = new PrintWriter(Entities.network.getSocket().getOutputStream());
					writer.println("stopMovie");
					writer.flush();
					Thread.sleep(2000);
					while(Entities.network.getSocket().getInputStream().available() > 0)
						ois.readObject();
				}catch(Exception ex){}
				
				playMovie = false;
				startActivity(new Intent(MovieActivity.this, BrowseActivity.class));
			}
		}
		
		});
	}
}
